package org.example.lease.service.impl;

import org.example.common.minio.MinioProperties;
import org.example.lease.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.ServerException;
import io.minio.errors.XmlParserException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 宋孟林
 * @description
 * @date: 2025/5/12 16:52
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Resource
    private MinioProperties minioProperties;
    @Resource
    private MinioClient minioClient;

    /**
     * 上传图片并且获取图片url
     * @param file file
     * @return url
     */
    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String bucketName = minioProperties.getBucketName();
        //判断存储桶是否存在
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        //如果不存在则创建桶
        if (!exists){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName)
                    .config(createBucketPolicy(bucketName)).build());
        }
        //存储桶中的文件名
        String fileName = new SimpleDateFormat("yyyyMMdd")
                .format(new Date()) + UUID.randomUUID() + "-" + file.getOriginalFilename();
        //存储一个新的图片对象到MinIO中
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName) //设置上传的存储桶
                        .object(fileName) //设置上传的文件名
                        .stream(file.getInputStream(), file.getSize(), -1) //上传的文件数据流，获取文件的输入流，文件的总大小，-1 代表让MinIO自己选择分片大小
                        .contentType(file.getContentType()) //设置对象的Content-Type(MIME类型)
                        .build()
        );
        //String.join(delimiter, element1, element2, element3, ...) join方法用于获取多个元素之间用delimiter连接的string
        //在这里是为了返回图片的URL，由端点--存储通--文件名 组成的URL
        String imageURL = String.join("/", minioProperties.getEndpoint(), bucketName, fileName);
        log.info("文件上传成功，地址为：{}", imageURL);
        return imageURL;
    }

    /**
     * 使用string的方法str.formatted(string)会将调用者str中的内容%s替换为方法中的参数
     * @param bucketName name
     * @return policy
     */
    public String createBucketPolicy(String bucketName){
        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }


}
